package com.jm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jm.common.exception.ServiceException;
import com.jm.common.util.entity.SelectCondition;
import com.jm.dao.AdminMapper;
import com.jm.pojo.Admin;
import com.jm.service.AdminService;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 * 管理员业务
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {


    /**
     * 检查用户名是否存在于数据库中
     *
     * @param username 需要被检查的用户名
     * @return 是否存在
     */
    @Override
    public boolean checkUsernameIsExists(String username) {
        if (username == null || "".equals(username)) throw new ServiceException("需要被检查的用户名为空,检查失败");
//        构造条件
        LambdaQueryWrapper<Admin> qw = new LambdaQueryWrapper<>();
        qw.eq(true, Admin::getUsername, username);
        Admin admin = getOne(qw);
        if (admin == null) return false;
        return true;
    }

    /**
     * 登录处理
     *
     * @param username 用户名
     * @param password 密码
     * @return 根据用户名密码查询到的管理员对象
     */
    @Override
    public Admin getLogin(String username, String password) {
        if (username == null || username.length() == 0) throw new ServiceException("用户名不能为为空");
        if (password == null || password.length() == 0) throw new ServiceException("密码不能为空");
//        构造条件
        LambdaQueryWrapper<Admin> qw = new LambdaQueryWrapper<>();
        qw.eq(true, Admin::getUsername, username)
                .eq(true, Admin::getPassword, password);
        return getOne(qw);
    }

    /**
     * 分页条件查询
     *
     * @param condition 条件对象
     * @return 查询结果
     */
    @Override
    public IPage<Admin> selectByPageCondition(SelectCondition condition) {
        Long currentPage = condition.getPage();
        Long pageSize = condition.getPageSize();
//        判空
        if (currentPage == null || pageSize == null)
            throw new ServiceException("分页分页条件出现错误");
//        构造分页对象
        IPage<Admin> page = new Page<>(currentPage, pageSize);
//        构造查询条件
        LambdaQueryWrapper<Admin> qw = new LambdaQueryWrapper<>();
        qw.like(condition.getName() != null, Admin::getName, condition.getName());
//        进行查询
        page(page, qw);
        return page;
    }
}
